#include "StereoView.h"

namespace stereo{

	StereoView::StereoView(){}

	StereoView::StereoView(float _zNear, float _zFar, int _width, int _height) : separation(0.0f)
	{
		vergence = 0.0f;
		width = _zFar;
		zNear = _zNear;
		zFar = _zFar;
		//square off windows to start
		for(int i = 0; i < 2; ++i){
			pixelsWidth[i] = _width;
			pixelsHeight[i] = _height;
		}
	}

	void StereoView::getLeftFrustum( float& _left, float& _right, float& _bottom, float& _top,
								float& _near, float& _far)
	{
		float left_v = (-width + separation)/2.0f;
		float right_v = (width + separation)/2.0f;
		_left = left_v / vergence * zNear;
		_right = (right_v + separation)/vergence * zNear;
#ifdef DEBUG_STEREO1
		std::cerr << "Left - Vergence: " << vergence << " Width: " << width
			<< " L_v: " << left_v << " R_v: " << right_v << " L: " << _left
			<< " R: " << _right << std::endl;
#endif
		_top = aspectRatio[0] * fabs(_right-_left)/2.0f;
		_bottom = -_top;
		_near = zNear;
		_far = zFar;
		return;
	}

	void StereoView::getRightFrustum(float& _left, float& _right, float& _bottom, float& _top,
									 float& _near, float& _far)
	{
		float left_v = (-width + separation)/2.0f;
		float right_v = (width - separation)/2.0f;
		_left = (left_v - separation)/vergence * zNear;
		_right = right_v/vergence * zNear;
#ifdef DEBUG_STEREO1
		std::cerr << "Right - Vergence: " << vergence << " Width: " << width
		<< " L_v: " << left_v << " R_v: " << right_v << " L: " << _left
		<< " R: " << _right << std::endl;
#endif
		_top = aspectRatio[1] * fabs(_right - _left)/2.0f;
		_bottom = -_top;
		_near = zNear;
		_far = zFar;
	}

	void StereoView::setGLFrustum(int _camera)
	{
		GLfloat left, right, bottom, top, near, far;
		if( _camera == 0){
			getLeftFrustum(left, right, bottom, top, near, far);
		} else {
			getRightFrustum(left, right, bottom, top, near, far);
		}
		//We only deal with frutums here.
		glFrustum(left, right, bottom, top, near, far);
		return;
	}

	void StereoView::setSeparation(float _separation)
	{
		if(_separation <= 0.0f) _separation = 0.0f;
		separation = _separation;
		return;
	}

	void StereoView::addSeparation(float _add)
	{
		if(separation + _add < 0.0f){
			separation = 0.0f;
		} else {
			separation += _add;
		}
		std::cerr << "Separation: " << separation << std::endl;
		return;
	}

	void StereoView::moveVergence(float _t)
	{
		//we do all of the math on our own in Game.cpp
		//just increment the value by _t
		vergence+=_t;
		return;
	}
}